<template>
  <Dialog title="基础信息" v-model="dialogVisible" width="80%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <div class="section-title">基础信息</div>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="供应商名称:" prop="name">
            <el-input v-model="formData.name" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商分类:" prop="supplierClassCode">
            <el-select v-model="formData.supplierClassCode" placeholder="请选择供应商分类" style="width: 100%">
              <el-option 
              v-for="item in classList"
              :key="item"
              :label="item"
              :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="经营范围:" prop="range">
            <el-input v-model="formData.range" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司规模:" prop="scale">
            <el-input v-model="formData.scale" placeholder="请输入" />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="公司邮编:" prop="postal">
            <el-input v-model="formData.postal" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司电话:" prop="phone">
            <el-input v-model="formData.phone" placeholder="请输入" />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="公司传真:" prop="fax">
            <el-input v-model="formData.fax" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司网站:" prop="website">
            <el-input v-model="formData.website" placeholder="请输入" />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="国家地区:" prop="country">
            <el-input v-model="formData.country" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所在时区:" prop="timeZone">
            <el-input v-model="formData.timeZone" placeholder="请输入" />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="所在城市:" prop="city">
            <el-input v-model="formData.city" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="港口:" prop="harbor">
            <el-input v-model="formData.harbor" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 独占一行的表单项 -->
      <el-form-item label="详细地址:" prop="addressPermanent">
        <el-input v-model="formData.addressPermanent" placeholder="请输入" />
      </el-form-item>
      
      <el-form-item label="备注:" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入" type="textarea" />
      </el-form-item>

      <!-- 联系人部分 -->
      <div class="form-section">
        <div class="section-title">联系人</div>
        <el-row>
          <div style="float: left; margin-top: 10px;">
            <el-button type="primary" @click="openContactForm('create')">新增</el-button>
            <el-button 
              style="
                background-color: transparent;
                border: 1px solid #409eff;
                color: #409eff;
              "
              type="primary"
              plain
              :disabled="selectedContactIds.length !== 1" 
              @click="openContactForm('update', selectedContactIds[0])"
            >
              编辑
            </el-button>
            <el-button 
              style="
                background-color: transparent;
                border: 1px solid #409eff;
                color: #409eff;
              "
              type="primary"
              plain
              :disabled="selectedContactIds.length === 0" 
              @click="batchDeleteContacts"
            >
              删除
            </el-button>
          </div>
        </el-row>
        
        <el-table 
          :data="contacts" 
          border 
          style="width: 100%"
          @selection-change="handleContactSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="name" label="联系人" width="80" align="center"/>
          <el-table-column prop="sex" label="性别" width="60" align="center">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.sex" />
            </template>
          </el-table-column>
          <el-table-column prop="position" label="职务" width="120" align="center"/>
          <el-table-column prop="email" label="邮箱" width="150" align="center"/>
          <el-table-column prop="landline" label="座机" width="120" align="center"/>
          <el-table-column prop="phone" label="移动电话" width="120" align="center"/>
          <el-table-column prop="facebook" label="Facebook" width="120" align="center"/>
          <el-table-column prop="ins" label="ins" width="120" align="center"/>
          <el-table-column prop="tiktok" label="TIKTOK" width="120" align="center"/>
          <el-table-column prop="youtube" label="Youtube" width="120" align="center"/>
          <el-table-column prop="linkedin" label="Linkedin" width="120" align="center"/>
          <el-table-column prop="remark" label="备注" width="120" align="center"/>
        </el-table>
      </div>
    </el-form>
    
    <template #footer>
      <div style="display: flex; justify-content: center; gap: 16px;">
        <el-button @click="dialogVisible = false" size="large" style="width: 100px;">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="formLoading" size="large" style="width: 100px;">保 存</el-button>
      </div>
    </template>
  </Dialog>

  <!-- 联系人表单弹窗 -->
  <Dialog :title="contactDialogTitle" v-model="contactDialogVisible" width="800px">
    <el-form 
      ref="contactFormRef" 
      :model="contactFormData" 
      :rules="contactFormRules" 
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="contactFormData.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别:" prop="sex">
            <el-radio-group v-model="contactFormData.sex">
              <el-radio label="1">男</el-radio>
              <el-radio label="2">女</el-radio>
              <el-radio label="3">未知</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职务" prop="position">
            <el-input v-model="contactFormData.position" placeholder="请输入职务" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="contactFormData.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="座机" prop="landline">
            <el-input v-model="contactFormData.landline" placeholder="请输入座机" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="移动电话" prop="phone">
            <el-input v-model="contactFormData.phone" placeholder="请输入移动电话" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="Facebook" prop="facebook">
            <el-input v-model="contactFormData.facebook" placeholder="请输入Facebook" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="ins" prop="ins">
            <el-input v-model="contactFormData.ins" placeholder="请输入ins" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="TikTok" prop="tiktok">
            <el-input v-model="contactFormData.tiktok" placeholder="请输入TikTok" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Youtube" prop="youtube">
            <el-input v-model="contactFormData.youtube" placeholder="请输入Youtube" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="Linkedin" prop="linkedin">
            <el-input v-model="contactFormData.linkedin" placeholder="请输入Linkedin" />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="contactFormData.remark" placeholder="请输入备注" type="textarea" :rows="1" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <el-button @click="contactDialogVisible = false" width="100px">取 消</el-button>
      <el-button type="primary" @click="saveContact" style="margin-right: 100px;" width="100px">保 存</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { SupplierInfoApi, SupplierInfoVO } from '@/api/busipart/supplierinfo'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { ref, reactive } from 'vue'

/** 供应商管理 表单 */
defineOptions({ name: 'SupplierInfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
let classList = []
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const formData = ref({
  id: undefined,
  code: undefined,
  name: undefined,
  supplierClassCode: undefined,
  range: undefined,
  scale: undefined,
  postal: undefined,
  phone: undefined,
  fax: undefined,
  website: undefined,
  country: undefined,
  timeZone: undefined,
  city: undefined,
  harbor: undefined,
  addressPermanent: undefined,
  addressMail: undefined,
  sourceCode: undefined,
  industryCode: undefined,
  priorityCode: undefined,
  starCode: undefined,
  stageCode: undefined,
  statusCode: undefined,
  remark: undefined,
})

// 联系人相关状态
const contacts = ref([])
const selectedContactIds = ref([])
const contactDialogVisible = ref(false)
const contactDialogTitle = ref('')
const contactFormRef = ref()
const contactFormData = ref({
  name: '',
  sex: '1',
  position: '',
  email: '',
  landline: '',
  phone: '',
  facebook: '',
  ins: '',
  tiktok: '',
  youtube: '',
  linkedin: '',
  remark: ''
})

// 表单验证规则
const formRules = reactive({})

// 联系人表单验证规则
const contactFormRules = reactive({
  name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  phone: [{ required: true, message: '移动电话不能为空', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }]
})

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async () => {
  
  dialogVisible.value = true
  resetForm()
  classList= await SupplierInfoApi.getClassList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 处理联系人选择变化 */
const handleContactSelectionChange = (val) => {
  selectedContactIds.value = val.map(item => item.id)
}

/** 打开联系人表单 */
const openContactForm = (type, id) => {
  contactDialogTitle.value = type === 'create' ? '新增联系人' : '编辑联系人'
  contactDialogVisible.value = true
  
  if (type === 'create') {
    contactFormData.value = {
      name: '',
      sex: '1',
      position: '',
      email: '',
      landline: '',
      phone: '',
      facebook: '',
      ins: '',
      tiktok: '',
      youtube: '',
      linkedin: '',
      remark: ''
    }
  } else {
    const contact = contacts.value.find(item => item.id === id)
    if (contact) {
      contactFormData.value = { ...contact }
    }
  }
}

/** 保存联系人 */
const saveContact = async () => {
  await contactFormRef.value.validate()
  
  if (contactDialogTitle.value === '新增联系人') {
    // 新增联系人
    contacts.value.push({
      id: Date.now(), // 临时ID
      ...contactFormData.value
    })
  } else {
    // 更新联系人
    const index = contacts.value.findIndex(item => item.id === selectedContactIds.value[0])
    if (index !== -1) {
      contacts.value[index] = {
        ...contacts.value[index],
        ...contactFormData.value
      }
    }
  }
  
  contactDialogVisible.value = false
  message.success('联系人保存成功')
}

/** 批量删除联系人 */
const batchDeleteContacts = () => {
  if (selectedContactIds.value.length === 0) {
    message.warning('请至少选择一条联系人记录')
    return
  }
  
  contacts.value = contacts.value.filter(
    item => !selectedContactIds.value.includes(item.id)
  )
  selectedContactIds.value = []
  message.success(`已删除 ${selectedContactIds.value.length} 条联系人记录`)
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      ...formData.value,
      listSupplierContactsSaveReqVO: contacts.value
    } as unknown as SupplierInfoVO
    
    await SupplierInfoApi.createSupplierInfo(data)
    message.success(t('common.createSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    name: undefined,
    supplierClassCode: undefined,
    range: undefined,
    scale: undefined,
    postal: undefined,
    phone: undefined,
    fax: undefined,
    website: undefined,
    country: undefined,
    timeZone: undefined,
    city: undefined,
    harbor: undefined,
    addressPermanent: undefined,
    addressMail: undefined,
    sourceCode: undefined,
    industryCode: undefined,
    priorityCode: undefined,
    starCode: undefined,
    stageCode: undefined,
    statusCode: undefined,
    remark: undefined,
  }
  contacts.value = []
  selectedContactIds.value = []
  formRef.value?.resetFields()
}
</script>

<style scoped>
.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #000000;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.form-section {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
</style>